package cn.car.biz.carAccess.support.abs;

import cn.car.biz.carAccess.support.PlateDetectedSupport;
import cn.car.constants.CarAccessConstants;
import cn.car.domains.ctx.PlateDetectedContext;
import cn.car.domains.entity.CameraInfoEntity;
import cn.car.domains.entity.VehicleCommonInfoEntity;
import cn.car.domains.entity.VehicleCommonLedgerInfoEntity;
import cn.car.domains.info.InternalVehicleInfo;
import cn.car.exception.CarAccessControlException;
import cn.car.service.VehicleCommonLedgerInfoService;
import cn.car.service.config.SystemConfig;
import cn.car.utils.Base64ToImageUtil;
import cn.car.utils.CarStringUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson2.JSONObject;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;

import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.function.Supplier;

@Slf4j
public abstract class AbstractSupport implements PlateDetectedSupport {

    private static final Supplier<String> IMAGE_LEDGER = () -> String.join(File.separator, CarAccessConstants.getPictureFilePath().get(), "ledger");


    @Resource
    private VehicleCommonLedgerInfoService vehicleCommonLedgerInfoService;

    @Resource
    private SystemConfig systemConfig;

    @Override
    public void processIn(PlateDetectedContext context) {
        VehicleCommonInfoEntity vehicleCommonInfoEntity = context.getVehicleCommonInfoEntity();

        Boolean enabled = vehicleCommonInfoEntity.getEnabled();

        if (!enabled) {
            throw CarAccessControlException.DELETE_NOT_EXIST.newInstance("车辆已失效");
        }

    }


    @Override
    public void processOut(PlateDetectedContext context) {
        VehicleCommonInfoEntity vehicleCommonInfoEntity = context.getVehicleCommonInfoEntity();

        if (vehicleCommonInfoEntity == null) {
            Boolean isValid = systemConfig.getExitPassValid().get();
            if (isValid) {
                throw CarAccessControlException.SYSTEM_ERROR.newInstance("车辆不存在，无法出场");
            }
        }

        context.setVehicleCommonInfoEntity(vehicleCommonInfoEntity);

    }

    @Override
    public void recordIn(PlateDetectedContext context) {

        InternalVehicleInfo vehicleInfo = context.getVehicleInfo();

        VehicleCommonInfoEntity vehicleCommonInfoEntity = context.getVehicleCommonInfoEntity();
        CameraInfoEntity cameraInfoEntity = context.getCameraInfoEntity();

        final String plateImgName = CarStringUtil.generateFileName(".jpeg");
        final String vehicleImgName = CarStringUtil.generateFileName(".jpeg");
        final String fileDir = String.join(File.separator, IMAGE_LEDGER.get());
        final String plateImgPath = String.join(File.separator, fileDir, plateImgName);
        final String vehicleImgPath = String.join(File.separator, fileDir, vehicleImgName);
        try {
            Base64ToImageUtil.saveBase64ImageToFile(vehicleInfo.getPlateImgBase64(), plateImgPath);
            Base64ToImageUtil.saveBase64ImageToFile(vehicleInfo.getVehicleImgBase64(), vehicleImgPath);
        } catch (IOException e) {
            log.error("[GateCarAccessorNormal recordIn] saveBase64ImageToFile error request: e" + JSONObject.toJSONString(context), e);
        }

        VehicleCommonLedgerInfoEntity ledgerInfoEntity = new VehicleCommonLedgerInfoEntity();
        ledgerInfoEntity.setVehicleNumber(vehicleCommonInfoEntity.getVehicleNumber());
        ledgerInfoEntity.setVehicleType(vehicleCommonInfoEntity.getVehicleType());
        ledgerInfoEntity.setEntryTime(new Date());
        ledgerInfoEntity.setEntryCameraIp(cameraInfoEntity.getCameraIp());
        ledgerInfoEntity.setEntryOperator(StrUtil.isEmpty(context.getManualOperator()) ? "SYSTEM" : context.getManualOperator());
        ledgerInfoEntity.setEntryPlateImgUrl(plateImgPath);
        ledgerInfoEntity.setEntryVehicleImgUrl(vehicleImgPath);
        ledgerInfoEntity.setEntryRoadCode(cameraInfoEntity.getRoadCode());
        ledgerInfoEntity.setEntryExitCode(cameraInfoEntity.getEntryExitCode());
        vehicleCommonLedgerInfoService.insert(ledgerInfoEntity);
        context.setVehicleCommonLedgerInfoEntity(ledgerInfoEntity);
    }


    @Override
    public void recordOut(PlateDetectedContext context) {
        InternalVehicleInfo vehicleInfo = context.getVehicleInfo();

        VehicleCommonInfoEntity vehicleCommonInfoEntity = context.getVehicleCommonInfoEntity();
        CameraInfoEntity cameraInfoEntity = context.getCameraInfoEntity();

        final String plateImgName = CarStringUtil.generateFileName(".jpeg");
        final String vehicleImgName = CarStringUtil.generateFileName(".jpeg");
        final String fileDir = String.join(File.separator, IMAGE_LEDGER.get());
        final String plateImgPath = String.join(File.separator, fileDir, plateImgName);
        final String vehicleImgPath = String.join(File.separator, fileDir, vehicleImgName);
        try {
            Base64ToImageUtil.saveBase64ImageToFile(vehicleInfo.getPlateImgBase64(), plateImgPath);
            Base64ToImageUtil.saveBase64ImageToFile(vehicleInfo.getVehicleImgBase64(), vehicleImgPath);
        } catch (IOException e) {
            log.error("[GateCarAccessorNormal recordIn] saveBase64ImageToFile error request: e" + JSONObject.toJSONString(context), e);
        }


        VehicleCommonLedgerInfoEntity ledgerInfoEntity = vehicleCommonLedgerInfoService.getLastLedgerByVehicleNumber(vehicleCommonInfoEntity.getVehicleNumber());

        if (ledgerInfoEntity == null || ledgerInfoEntity.getExitTime() != null) {
            //新增一条记录

            VehicleCommonLedgerInfoEntity newVehicleCommonLedger = new VehicleCommonLedgerInfoEntity();
            newVehicleCommonLedger.setVehicleNumber(vehicleCommonInfoEntity.getVehicleNumber());
            newVehicleCommonLedger.setVehicleType(vehicleCommonInfoEntity.getVehicleType());
            newVehicleCommonLedger.setExitTime(new Date());
            newVehicleCommonLedger.setExitCameraIp(cameraInfoEntity.getCameraIp());
            newVehicleCommonLedger.setExitOperator(StrUtil.isEmpty(context.getManualOperator()) ? "SYSTEM" : context.getManualOperator());
            newVehicleCommonLedger.setExitPlateImgUrl(plateImgPath);
            newVehicleCommonLedger.setExitVehicleImgUrl(vehicleImgPath);
            newVehicleCommonLedger.setExitRoadCode(cameraInfoEntity.getRoadCode());
            newVehicleCommonLedger.setExitEntryExitCode(cameraInfoEntity.getEntryExitCode());
            vehicleCommonLedgerInfoService.insert(newVehicleCommonLedger);
            context.setVehicleCommonLedgerInfoEntity(newVehicleCommonLedger);
        } else {
            //更新上一条记录出厂信息=
            ledgerInfoEntity.setExitTime(new Date());
            ledgerInfoEntity.setExitCameraIp(cameraInfoEntity.getCameraIp());
            ledgerInfoEntity.setExitOperator(StrUtil.isEmpty(context.getManualOperator()) ? "SYSTEM" : context.getManualOperator());
            ledgerInfoEntity.setExitPlateImgUrl(plateImgPath);
            ledgerInfoEntity.setExitVehicleImgUrl(vehicleImgPath);
            ledgerInfoEntity.setExitRoadCode(cameraInfoEntity.getRoadCode());
            ledgerInfoEntity.setExitEntryExitCode(cameraInfoEntity.getEntryExitCode());
            vehicleCommonLedgerInfoService.update(ledgerInfoEntity);
            context.setVehicleCommonLedgerInfoEntity(ledgerInfoEntity);
        }

    }


}
